package com.streamer.app.fragment

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.streamer.app.R
import com.streamer.app.adapter.ProductListAdapter
import com.streamer.app.bean.LiveBean
import com.streamer.app.bean.liveProductBean
import com.streamer.app.model.MyViewModel
import com.streamer.app.utils.api.ViewModel

// 定义上架参数数据类
data class PutOnShelfParams(
    val listingType: String, // "indirect" 或 "long_term"
    val indirectCount: String? = null, // 间接次数
    val indirectTime: String? = null   // 间接时间
)

// 定义商品操作接口
interface ProductActionListener {
    fun onPutOnShelf(product: liveProductBean, params: PutOnShelfParams)
    fun onTakeOffShelf(product: liveProductBean)
    fun onExplainProduct(product: liveProductBean)
    fun onViewProduct(product: liveProductBean)
}

class ProductListFragment : androidx.fragment.app.Fragment() {

    private lateinit var viewModel: ViewModel
    private var adapter: ProductListAdapter? = null
    private var isOnSale: Boolean = true
    private var roomId: String = ""
    private val pageSize = 10
    private val currentPage = 1
    private var mliveData: LiveBean? = null

    // 添加接口回调
    private var productActionListener: ProductActionListener? = null
    private val myViewModel: MyViewModel by activityViewModels()

    companion object {
        private const val ARG_IS_ON_SALE = "arg_is_on_sale"
        private const val ARG_ROOM_ID = "arg_room_id"

        fun newInstance(
            fragmentActivity: Activity, isOnSale: Boolean, roomId: String
        ): ProductListFragment {
            return ProductListFragment().apply {
                arguments = Bundle().apply {
                    putBoolean(ARG_IS_ON_SALE, isOnSale)
                    putString(ARG_ROOM_ID, roomId)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            isOnSale = it.getBoolean(ARG_IS_ON_SALE)
            roomId = it.getString(ARG_ROOM_ID, "") ?: ""
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_product_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化ViewModel
        viewModel = ViewModel()

        val recyclerView = view.findViewById<RecyclerView>(R.id.rv_product_list)
        recyclerView.layoutManager = LinearLayoutManager(context)

        // 创建适配器（先使用空数据），根据 isOnSale 决定行为
        adapter = ProductListAdapter(mutableListOf(), isOnSale) { product, action ->
            when {
                action == "take_off_shelf" -> {
                    // 通过接口回调处理下架
                    productActionListener?.onTakeOffShelf(product)
                    // 或者直接调用API
                    viewModel.liveProductPutaway(product.id)
                    // 刷新两端计数
                    refreshCounts()
                }

                action == "explain_product" -> {
                    // 通过接口回调处理讲解商品
                    productActionListener?.onExplainProduct(product)
                    // 调用API
                    viewModel.taught(product.id)
                    // 商品讲解不一定改变上下架状态，这里不刷新计数
                }

                action == "explain_cancel_product" -> {
                    // 通过接口回调处理讲解商品
                    productActionListener?.onExplainProduct(product)
                    // 调用API
                    viewModel.cancelTaught(product.id)
                    // 讲解取消不改变上下架，忽略计数
                }

                action == "view_product" -> {
                    // 通过接口回调处理查看商品
                    productActionListener?.onViewProduct(product)
                    // 或者直接显示详情
                    showProductDetailDialog(product)
                }

                action.startsWith("put_on_shelf_") -> {
                    // 解析上架参数
                    val params = action.split("|")
                    if (params[0] == "put_on_shelf_indirect" && params.size >= 3) {
                        // 间接上架
                        val putOnShelfParams = PutOnShelfParams(
                            listingType = "indirect",
                            indirectCount = params[1],
                            indirectTime = params[2]
                        )

                        // 通过接口回调处理上架
                        productActionListener?.onPutOnShelf(product, putOnShelfParams)
                        // 或者直接调用API
                        viewModel.liveProductPutaway(
                            id = product.id,
                            showType = "1",
                            interval = params[1],
                            intervalTime = params[2]
                        )
                        // 刷新两端计数
                        refreshCounts()

                        // 打印参数信息
                        Log.d("ProductListFragment", "间接上架参数: $putOnShelfParams")
//                        ( fragmentActivity as LiveStreamActivity).updateProductCounts()

                    } else if (params[0] == "put_on_shelf_long_term") {
                        // 长期上架
                        val putOnShelfParams = PutOnShelfParams(
                            listingType = "long_term"
                        )

                        // 通过接口回调处理上架
                        productActionListener?.onPutOnShelf(product, putOnShelfParams)
//                        ( fragmentActivity as LiveStreamActivity)?.updateProductCounts()

                        // 或者直接调用API
                        viewModel.liveProductPutaway(
                            id = product.id, showType = "2"
                        )
                        // 刷新两端计数
                        refreshCounts()

                    }
                }
            }
        }

        viewModel.PublishCouponLV.observe(viewLifecycleOwner) {
            getData()
            // 刷新两端计数（以防存在优惠券发布导致商品状态变更的业务）
            refreshCounts()
        }
        recyclerView.adapter = adapter
        viewModel.getLiveData()

        viewModel.LiveInfoDataLV.observe(requireActivity()) {
            if (it != null) {
                mliveData = it
                if (isOnSale) {
                    // 仅观察售卖中列表
                    viewModel.onLiveProductBeanLV.observe(viewLifecycleOwner) { pageDataResult ->
                        if (pageDataResult?.rows != null) {
                            val productList = pageDataResult.rows
                            myViewModel.updateMessage(productList.size.toString())
                            adapter?.updateProducts(
                                productList,
                                mliveData!!.isItemPriceEnabled,
                                mliveData!!.isItemSoldNumEnabled
                            )
                            adapter?.notifyDataSetChanged()
                            // 刷新对侧计数
                            refreshCounts()
                        } else {
                            myViewModel.updateMessage("0")
                            adapter?.updateProducts(emptyList())
                            refreshCounts()
                        }
                    }
                    viewModel.liveProductBeanLV.observe(viewLifecycleOwner) { pageDataResult ->

                        if (pageDataResult?.rows != null) {
                            val productList = pageDataResult.rows
                            myViewModel.updateMessage2(productList.size.toString())
                        }
                    }
                } else {
                    // 仅观察已下架列表
                    viewModel.liveProductBeanLV.observe(viewLifecycleOwner) { pageDataResult ->
                        if (pageDataResult?.rows != null) {
                            val productList = pageDataResult.rows
                            myViewModel.updateMessage2(productList.size.toString())
                            adapter?.updateProducts(
                                productList,
                                mliveData!!.isItemPriceEnabled,
                                mliveData!!.isItemSoldNumEnabled
                            )
                            adapter?.notifyDataSetChanged()
                            // 刷新对侧计数
                            refreshCounts()
                        } else {
                            myViewModel.updateMessage2("0")
                            adapter?.updateProducts(emptyList())
                            refreshCounts()
                        }
                    }

                    viewModel.onLiveProductBeanLV.observe(viewLifecycleOwner) { pageDataResult ->
                        if (pageDataResult?.rows != null) {
                            val productList = pageDataResult.rows
                            myViewModel.updateMessage(productList.size.toString())
                        }
                    }
                }
            }
        }

    }

    override fun onResume() {
        super.onResume()
        getData()
    }


    private fun getData() {
            viewModel.onLiveProductsPageQuery(pageSize, currentPage, roomId, "1")
            viewModel.liveProductsPageQuery(pageSize, currentPage, roomId, "0")
    }

    private fun refreshCounts() {
        // 使用传入的 roomId，避免依赖 mliveData 初始化时序
        if (roomId.isNotEmpty()) {
            viewModel.getOnSaleProductCount(roomId)
            viewModel.getOffShelfProductCount(roomId)
        } else {
            mliveData?.id?.toString()?.let {
                viewModel.getOnSaleProductCount(it)
                viewModel.getOffShelfProductCount(it)
            }
        }
    }


    private fun showProductDetailDialog(product: liveProductBean) {

        val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(requireContext())
        val view = layoutInflater.inflate(R.layout.dialog_product_detail, null)
        dialog.setContentView(view)
        // 填充数据
        val ivProductImage = view.findViewById<android.widget.ImageView>(R.id.iv_product_image)
        val tvProductTitle = view.findViewById<android.widget.TextView>(R.id.tv_product_title)
        val tvProductQuota = view.findViewById<android.widget.TextView>(R.id.tv_product_quota)
        val tvProductSold = view.findViewById<android.widget.TextView>(R.id.tv_product_sold)
        val tvProductPrice = view.findViewById<android.widget.TextView>(R.id.tv_product_price)
        val tvProductDesc = view.findViewById<android.widget.TextView>(R.id.tv_product_desc)
        val tvCourseDetail = view.findViewById<android.widget.TextView>(R.id.tv_course_detail)
        val layoutCatalogToggle =
            view.findViewById<android.widget.LinearLayout>(R.id.layout_catalog_toggle)
        val layoutCatalogContent =
            view.findViewById<android.widget.LinearLayout>(R.id.layout_catalog_content)
        val ivCatalogArrow = view.findViewById<android.widget.ImageView>(R.id.iv_catalog_arrow)
        val ivClose = view.findViewById<android.widget.ImageView>(R.id.iv_close)

        // Tab相关视图
        val tvTabCourseDetail =
            view.findViewById<android.widget.TextView>(R.id.tv_tab_course_detail)
        val tvTabCourseCatalog =
            view.findViewById<android.widget.TextView>(R.id.tv_tab_course_catalog)
        val viewTabIndicator = view.findViewById<View>(R.id.view_tab_indicator)
        val layoutCourseCatalog =
            view.findViewById<android.widget.LinearLayout>(R.id.layout_course_catalog)

        // 示例填充
        tvProductTitle.text = product.title
        ivProductImage.apply {
            Glide.with(this).load(product.coverImage).into(this)
        }
        if (mliveData?.isItemPriceEnabled == true) {
            tvProductPrice.text = "¥${product.price}"

        } else {
            tvProductPrice.text = ""
        }
        tvProductDesc.text = product.description
//        tvCourseDetail.text = product.
        if (product.quota != 0) {
            tvProductQuota.text = "限购${product.quota}"
        }
        if (mliveData?.isItemSoldNumEnabled == true) {
            tvProductSold.text = "销量${product.virtualSales}"

        } else {
            tvProductSold.text = ""
        }

        // 关闭按钮
        ivClose.setOnClickListener { dialog.dismiss() }

        // 获取商品详细信息
        viewModel.getFullInfo(product.productId)
        viewModel.ProductBeanLV.observe(requireActivity()) { result ->
            if (result?.data != null) {
                val productData = result.data

                // 添加详细的调试日志
                Log.d("ProductListFragment", "=== 商品详情数据调试 ===")
                Log.d("ProductListFragment", "商品标题: ${productData.products.title}")
                Log.d("ProductListFragment", "商品描述: ${productData.products.description}")
                Log.d(
                    "ProductListFragment",
                    "课程关系数量: ${productData.productCourseRelations.size}"
                )

                // 检查课程关系数据
                productData.productCourseRelations.forEachIndexed { index, relation ->
                    Log.d("ProductListFragment", "课程关系${index + 1}:")
                    Log.d("ProductListFragment", "  - 课程ID: ${relation.courseId}")
                    Log.d("ProductListFragment", "  - 课程标题: ${relation.title}")
                    Log.d("ProductListFragment", "  - 课程描述: ${relation.description}")
                    Log.d("ProductListFragment", "  - 章节数量: ${relation.coursesChapters.size}")

                    // 检查章节数据
                    relation.coursesChapters.forEachIndexed { chapterIndex, chapter ->
                        Log.d("ProductListFragment", "  章节${chapterIndex + 1}:")
                        Log.d("ProductListFragment", "    - 章节ID: ${chapter.chapterId}")
                        Log.d("ProductListFragment", "    - 章节标题: ${chapter.title}")
                        Log.d(
                            "ProductListFragment", "    - 小节数量: ${chapter.coursesKnobbles.size}"
                        )

                        // 检查小节数据
                        chapter.coursesKnobbles.forEachIndexed { knobbleIndex, knobble ->
                            Log.d("ProductListFragment", "    小节${knobbleIndex + 1}:")
                            Log.d("ProductListFragment", "      - 小节ID: ${knobble.knobbleId}")
                            Log.d("ProductListFragment", "      - 小节标题: ${knobble.title}")
                            Log.d(
                                "ProductListFragment",
                                "      - 内容数量: ${knobble.coursesContents.size}"
                            )
                        }
                    }
                }

                // 更新课程详情
                if (!productData.products.description.isNullOrEmpty()) {
                    tvCourseDetail.text = productData.products.description
                } else {
                    tvCourseDetail.text = "暂无课程详情"
                }

                // 更新课程目录
                if (productData.productCourseRelations.isNotEmpty()) {
                    val courseRelation = productData.productCourseRelations[0] // 取第一个课程
                    val chapters = courseRelation.coursesChapters

                    Log.d("ProductListFragment", "=== 课程目录渲染 ===")
                    Log.d("ProductListFragment", "课程标题: ${courseRelation.title}")
                    Log.d("ProductListFragment", "章节数量: ${chapters.size}")

                    // 检查chapters是否为空
                    if (chapters.isNotEmpty()) {
                        Log.d("ProductListFragment", "开始渲染课程目录...")

                        // 清空并重新添加课程章节
                        val layoutCourseCatalog =
                            view.findViewById<LinearLayout>(R.id.layout_course_catalog)
                        layoutCourseCatalog.removeAllViews()

                        // 添加课程目录标题
                        val titleView = TextView(requireContext()).apply {
                            text = "课程目录（${chapters.size}）"
                            setTextColor(android.graphics.Color.parseColor("#222222"))
                            textSize = 15f
                            setTypeface(null, android.graphics.Typeface.BOLD)
                            setPadding(0, 0, 0, 48) // 48dp = 12dp * 4
                        }
                        layoutCourseCatalog.addView(titleView)

                        // 添加每个章节
                        chapters.forEachIndexed { index, chapter ->
                            Log.d("ProductListFragment", "渲染章节${index + 1}: ${chapter.title}")
                            Log.d(
                                "ProductListFragment",
                                "章节${index + 1}小节数量: ${chapter.coursesKnobbles.size}"
                            )

                            val chapterCard = createChapterCard(chapter, index + 1)
                            layoutCourseCatalog.addView(chapterCard)
                        }

                        Log.d("ProductListFragment", "课程目录渲染完成")
                    } else {
                        Log.d("ProductListFragment", "章节数据为空，显示空状态")

                        // 如果没有章节数据，显示提示信息
                        val layoutCourseCatalog =
                            view.findViewById<LinearLayout>(R.id.layout_course_catalog)
                        layoutCourseCatalog.removeAllViews()

                        val emptyView = TextView(requireContext()).apply {
                            text = "暂无课程目录"
                            setTextColor(android.graphics.Color.parseColor("#888888"))
                            textSize = 14f
                            gravity = android.view.Gravity.CENTER
                            setPadding(0, 48, 0, 48) // 12dp top and bottom
                        }
                        layoutCourseCatalog.addView(emptyView)
                    }
                } else {
                    Log.d("ProductListFragment", "没有课程关系数据")
                }
            } else {
                Log.d("ProductListFragment", "API返回数据为空")
            }
        }

        // Tab切换逻辑
        var currentTab = 0 // 0: 课程详情, 1: 课程目录
        fun updateTabUI() {
            if (currentTab == 0) {
                // 课程详情tab激活
                tvTabCourseDetail.setTextColor(android.graphics.Color.parseColor("#222222"))
                tvTabCourseDetail.textSize = 15f
                tvTabCourseDetail.setTypeface(null, android.graphics.Typeface.BOLD)
                tvTabCourseCatalog.setTextColor(android.graphics.Color.parseColor("#888888"))
                tvTabCourseCatalog.textSize = 15f
                tvTabCourseCatalog.setTypeface(null, android.graphics.Typeface.NORMAL)
                tvCourseDetail.visibility = View.VISIBLE
                layoutCourseCatalog.visibility = View.GONE
                // 移动下划线到第一个tab
                viewTabIndicator.layoutParams = viewTabIndicator.layoutParams.apply {
                    width = 0
                    (this as android.widget.LinearLayout.LayoutParams).weight = 1f
                }
            } else {

                // 课程目录tab激活
                tvTabCourseDetail.setTextColor(android.graphics.Color.parseColor("#888888"))
                tvTabCourseDetail.textSize = 15f
                tvTabCourseDetail.setTypeface(null, android.graphics.Typeface.NORMAL)
                tvTabCourseCatalog.setTextColor(android.graphics.Color.parseColor("#222222"))
                tvTabCourseCatalog.textSize = 15f
                tvTabCourseCatalog.setTypeface(null, android.graphics.Typeface.BOLD)
                tvCourseDetail.visibility = View.GONE
                layoutCourseCatalog.visibility = View.VISIBLE
                // 移动下划线到第二个tab
                viewTabIndicator.layoutParams = viewTabIndicator.layoutParams.apply {
                    width = 0
                    (this as android.widget.LinearLayout.LayoutParams).weight = 1f
                    marginStart = 0
                    marginEnd = 0
                }
            }
        }

        // 设置tab点击事件
        tvTabCourseDetail.setOnClickListener {
            currentTab = 0
            updateTabUI()
        }
        tvTabCourseCatalog.setOnClickListener {
            currentTab = 1
            updateTabUI()
        }

        // 初始化tab状态
        updateTabUI()

        // 目录折叠
        var expanded = false
        layoutCatalogToggle.setOnClickListener {
            expanded = !expanded
            layoutCatalogContent.visibility = if (expanded) View.VISIBLE else View.GONE
            ivCatalogArrow.rotation = if (expanded) 180f else 0f
        }
        dialog.show()
    }

    // 创建章节卡片
    private fun createChapterCard(
        chapter: com.streamer.app.bean.CoursesChapter, chapterNumber: Int
    ): android.view.View {
        val cardView = androidx.cardview.widget.CardView(requireContext()).apply {
            layoutParams = android.view.ViewGroup.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT
            )
            radius = 32f // 8dp
            elevation = 8f // 2dp
            setCardBackgroundColor(android.graphics.Color.WHITE)
            setContentPadding(48, 48, 48, 48) // 12dp
        }

        val contentLayout = LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            layoutParams = android.view.ViewGroup.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }

        // 章节标题
        val chapterTitle = TextView(requireContext()).apply {
            text = "${chapterNumber}.0 ${chapter.title}"
            setTextColor(android.graphics.Color.parseColor("#222222"))
            textSize = 14f
            setTypeface(null, android.graphics.Typeface.BOLD)
            layoutParams = android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
            )
        }
        contentLayout.addView(chapterTitle)

        // 添加小节（如果有）
        if (chapter.coursesKnobbles != null && chapter.coursesKnobbles.isNotEmpty()) {
            chapter.coursesKnobbles.forEachIndexed { knobbleIndex, knobble ->
                val knobbleTitle = android.widget.TextView(requireContext()).apply {
                    text = "  ${chapterNumber}.${knobbleIndex + 1} ${knobble.title}"
                    setTextColor(android.graphics.Color.parseColor("#666666"))
                    textSize = 13f
                    setPadding(32, 16, 0, 8) // 8dp left padding, 4dp top, 0 right, 2dp bottom
                    layoutParams = android.widget.LinearLayout.LayoutParams(
                        android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                        android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                }
                contentLayout.addView(knobbleTitle)

                // 添加小节内容（如果有）
                if (knobble.coursesContents != null && knobble.coursesContents.isNotEmpty()) {
                    knobble.coursesContents.forEachIndexed { contentIndex, content ->
                        val contentTitle = android.widget.TextView(requireContext()).apply {
                            text =
                                "    ${chapterNumber}.${knobbleIndex + 1}.${contentIndex + 1} ${content.title}"
                            setTextColor(android.graphics.Color.parseColor("#888888"))
                            textSize = 12f
                            setPadding(
                                64, 8, 0, 4
                            ) // 16dp left padding, 2dp top, 0 right, 1dp bottom
                            layoutParams = android.widget.LinearLayout.LayoutParams(
                                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
                            )
                        }
                        contentLayout.addView(contentTitle)
                    }
                }
            }
        }

        cardView.addView(contentLayout)

        // 设置底部边距
        val marginLayoutParams = android.widget.LinearLayout.LayoutParams(
            android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
            android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
        )
        marginLayoutParams.bottomMargin = 32 // 8dp
        cardView.layoutParams = marginLayoutParams

        return cardView
    }
} 